import http
import json
import re

from django.contrib.auth import logout
from django.core.cache import cache
from django.http import JsonResponse
from django.views import View
from django.contrib.auth import models

from apps.areas.models import Area, Address

# 省联动
from utils.views import LoginRequiredJSONMixin


class AreasView(View):
    def get(self, request):
        # -- 缓存查找
        province_list = cache.get('provinces')

        # 1. 去数据库查询所有的省份数据
        # -- 没有缓存
        if not province_list:
            print('省正在缓存...')
            try:
                areas = Area.objects.filter(parent=None)
            except Exception as e:
                print(e)
                return JsonResponse({'code': 400, 'errmsg': '获取省份失败'})

            province_list = []
            for a in areas:
                province_list.append({'id': a.id, 'name': a.name})

            # 保存省缓存（string, data, time）
            cache.set('provinces', province_list, 3600 * 24 * 15)

            return JsonResponse({'code': 0, 'provice_list': province_list})

        # -- 有缓存
        return JsonResponse({'code': 0, 'province_list': province_list})


# 市区联动
class SubAreasView(View):
    def get(self, request, area_id):
        # -- 缓存查找
        subs = cache.get('cities_%s' % area_id)

        if not subs:
            print('市缓存中...')
            try:
                subareas = Area.objects.filter(parent_id=area_id)
            except Exception as e:
                print(e)
                return JsonResponse({'code': 0, 'errmsg': '获取市区失败, 网络异常'})

            subs = []
            for a in subareas:
                subs.append({'id': a.id, 'name': a.name})

            # -- 存储缓存
            cache.set('cities_%s' % area_id, subs, 3600 * 24 * 15)
        print('市已经缓存')
        return JsonResponse({'code': 0, 'sub_data': {'subs': subs}})


# 收货地址
class AddressView(LoginRequiredJSONMixin, View):
    # -- 添加收货地址
    def post(self, request):
        # 1. 获取数据
        data_dict = json.loads(request.body)
        print(data_dict)
        receiver = data_dict.get('receiver')  # 收货人
        province_id = data_dict.get('province_id')  # 省
        city_id = data_dict.get('city_id')  # 市
        district_id = data_dict.get('district_id')  # 区
        place = data_dict.get('place')  # 详细地址
        mobile = data_dict.get('mobile')  # 电话
        tel = data_dict.get('tel')  # 座机
        email = data_dict.get('email')  # 邮箱

        # 2. 校验
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return JsonResponse({'code': 400, 'errmsg': "数据不全"})

        # 3. 使用Address模型类添加数据
        try:
            address = Address.objects.create(user=request.user,
                                             title=receiver,
                                             receiver=receiver,
                                             province_id=province_id,
                                             city_id=city_id,
                                             district_id=district_id,
                                             place=place,
                                             mobile=mobile,
                                             tel=tel,
                                             email=email)
            # 设置address为默认地址
            request.user.default_address = address.id
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 505, 'errmsg': '保存失败'})

        # 4. 保存地址数据 province
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }
        print(address_dict)
        # 5. 返回数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'province': address_dict})

    # -- 获取收货地址
    def get(self, request):
        # 获取所有的用户对象
        user = request.user
        # 获取所有地址
        try:
            # addresses =Address.objects.filter(user=user)
            # models.  related_name='addresses'

            addresses = user.addresses.all().filter(is_deleted=False)
            # 存地址
            print(addresses)
            address_dict_list = []
            # 循环添加数据
            for address in addresses:
                address_dict = {
                    "id": address.id,
                    "title": address.title,
                    "receiver": address.receiver,
                    "province": address.province.name,
                    "city": address.city.name,
                    "district": address.district.name,
                    "place": address.place,
                    "mobile": address.mobile,
                    "tel": address.tel,
                    "email": address.email
                }
                # 拼接列表
                address_dict_list.insert(0, address_dict)

        except Exception as e:
            print(e)
            return JsonResponse({'code': 501, 'errmsg': '查询失败'})
        # print(address_dict_list)
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'addresses': address_dict_list,
                             'default_address_id': request.user.default_address})


# 默认地址
class DefaultView(LoginRequiredJSONMixin, View):
    def put(self, request, id):
        try:
            d = Address.objects.filter(id=id)
            # 设置address为默认地址
            print(d)
            request.user.default_address = d
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '设置默认地址失败'})

        return JsonResponse({'code': 0, 'errmsg': '设置默认地址成功'})


# 修改地址
class UpdataView(LoginRequiredJSONMixin, View):
    def put(self, request, id):
        # 1. 获取数据
        json_dict = json.loads(request.body.decode())
        receiver = json_dict.get('receiver')
        province_id = json_dict.get('province_id')
        city_id = json_dict.get('city_id')
        district_id = json_dict.get('district_id')
        place = json_dict.get('place')
        mobile = json_dict.get('mobile')
        tel = json_dict.get('tel')
        email = json_dict.get('email')

        # 2. 校验
        if not all([receiver, province_id, city_id, district_id, place, mobile]):
            return http.JsonResponse({'code': 400,
                                      'errmsg': '缺少必传参数'})

        # 3. 判断
        try:
            Address.objects.filter(id=id).update(
                user=request.user,
                title=receiver,
                receiver=receiver,
                province_id=province_id,
                city_id=city_id,
                district_id=district_id,
                place=place,
                mobile=mobile,
                tel=tel,
                email=email
            )
        except Exception as e:
            print(e)
            return http.JsonResponse({'code': 400, 'errmsg': '更新地址失败'})

        # 构造响应数据
        address = Address.objects.get(id=id)
        address_dict = {
            "id": address.id,
            "title": address.title,
            "receiver": address.receiver,
            "province": address.province.name,
            "city": address.city.name,
            "district": address.district.name,
            "place": address.place,
            "mobile": address.mobile,
            "tel": address.tel,
            "email": address.email
        }

        # 响应更新地址结果
        return JsonResponse({'code': 0, 'errmsg': '更新地址成功', 'address': address_dict})

    # 删除数据
    def delete(self, request, id):
        try:
            # 查询要删除的地址
            address = Address.objects.get(id=id)

            # 将地址逻辑删除设置为True
            print(address.is_deleted)
            address.is_deleted = True
            address.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '删除地址失败'})

        # 响应删除地址结果
        return JsonResponse({'code': 0, 'errmsg': '删除地址成功'})


# 修改标题
class UpdataTitle(View):
    def put(self, request, id):
        dict = json.loads(request.body)
        tits = dict.get('title')
        try:
            tit = Address.objects.get(id=id)
            tit.title = tits
            tit.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 0, 'errmsg': '修改标题失败'})

        return JsonResponse({'code': 0, 'errmsg': '修改成功'})


# 修改密码
class UpdataPwd(View):
    def put(self, request):
        # 修改密码前需要校验原始密码是否正确，以校验修改密码的用户身份。
        # 如果原始密码正确，再将新的密码赋值给用户。
        # 1. 获取
        dict = json.loads(request.body)
        old1 = dict.get('old_password')
        new1 = dict.get('new_password')
        new2 = dict.get('new_password2')

        # 2.　判空
        if not all([old1, new1, new2]):
            return JsonResponse({'code': 400, 'errmsg': '缺少指定参数'})

        print(old1)
        print()

        result = request.user.check_password(old1)  # 查询密码
        print(result)

        # 3.　校验
        if not result:  # 判断原密码
            print('原密码不正确')
            return JsonResponse({'code': 400, 'errmsg': '原密码不正确'})
        if new1 != new2:
            print('两次密码输入不一致')
            return JsonResponse({'code': 400, 'errmsg': '两次密码输入不一致'})

        # 4. 修改
        try:
            request.user.set_password(new1)
            request.user.save()
        except Exception as e:
            print(e)
            return JsonResponse({'code': 400, 'errmsg': '修改失败'})

        # 5. 退出登录
        logout(request)

        # 6. 返回跳转登录
        response = JsonResponse({'code': 0, 'errmsg': '修改成功'})
        # -- 清除ｃｏｏｋｉｅ
        response.delete_cookie('username')

        return response
